package com.sqm.service;

import com.sqm.config.BaseContext;
import com.sqm.model.Novel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * 功能:
 * 作者: 沙琪马
 * 日期: 2024/6/7 12:35
 */
@Service
@Slf4j
public class NovelService {
    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private ShujaService shujaService;

    public List<Novel> getNovels() {
        // 1.生成七个随机数，随机获取7本书
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.sample(7)
        );
        return mongoTemplate.aggregate(aggregation, "novels", Novel.class).getMappedResults();

    }

    public Page<Novel> getNovelsByType(String type, int page, int size) {
        // 1.构建查询条件
        Query query = new Query(new Criteria("type").is(type));
        long total = mongoTemplate.count(query, Novel.class);

        // Apply pagination
        Pageable pageable = PageRequest.of(page, size);
        query.with(pageable);
        if (total == 0) {
            return new PageImpl<>(null, pageable, total);
        }

        // 2.返回条件
        List<Novel> novels = mongoTemplate.find(query, Novel.class);
        return new PageImpl<>(novels, pageable, total);
    }

    public Page<Novel> getNovelsByName(String name, int page, int size) {
        // 1.构建查询条件
        Query query = new Query(new Criteria("title").regex(name));
        long total = mongoTemplate.count(query, Novel.class);

        Pageable pageable = PageRequest.of(page, size);
        query.with(pageable);
        List<Novel> novels = mongoTemplate.find(query, Novel.class);
        return new PageImpl<>(novels, pageable, total);
    }


}
